package com.itboye.textileexpres.main;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.app.ActionBar.LayoutParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.itboye.tbshopcar.listener.UIAlertView;
import com.itboye.textileexpes.beans.AppUpdateBean;
import com.itboye.textileexpes.beans.ColletionFenyeBeans;
import com.itboye.textileexpes.beans.GoodsTopBean;
import com.itboye.textileexpes.beans.NewsKefuBeans;
import com.itboye.textileexpes.beans.UserBean;
import com.itboye.textileexpes.presenter.AppUpdatePresenter;
import com.itboye.textileexpes.presenter.ColloctionPresenter;
import com.itboye.textileexpes.presenter.GoodsPresenter;
import com.itboye.textileexpes.presenter.MainPresenter;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseFragment;
import com.itboye.textileexpres.base.MainApplication;
import com.itboye.textileexpres.base.ResultEntity;
import com.itboye.textileexpres.base.SpPublicParams;
import com.itboye.textileexpres.login.LoginActivity;
import com.itboye.textileexpres.myset.ActivityCustomerService;
import com.itboye.textileexpres.top.ActivityCarmarSearch;
import com.itboye.textileexpres.top.ActivityTypeDetail;
import com.itboye.textileexpres.top.ActivityTypeTwoGoods;
import com.itboye.textileexpres.top.GoodsDetail;
import com.itboye.textileexpres.top.GoodsFragmentAdapter;
import com.itboye.textileexpres.util.ConnectionChangeReceiver;
import com.itboye.textileexpres.util.IsMobileNumPhone;
import com.itboye.textileexpres.util.MyToast;
import com.itboye.textileexpres.util.SPUtils;
import com.itboye.textileexpres.util.UpdateManager;
import com.itboye.textileexpres.widget.XListView;
import com.itboye.textileexpres.widget.XListView.IXListViewListener;
import com.itboye.textileexptes.config.GlobalConfig;
/**
 * 首页
 *
 */
public class GoodsFragment extends BaseFragment implements IXListViewListener,
		Observer {
	TextView title;
	ImageView back, img_other;
	EditText key_word;
	XListView xlist;
	GoodsFragmentAdapter adapter;
	PopupWindow popupWindow;
	View pop;
	LinearLayout no_interest;
	AppUpdatePresenter updatePresenter;
	String version;
	String update_log;
	UIAlertView dialog;
	ImageView carmar_img;
	ImageView type_img;
	GoodsPresenter goodsPresenter;
	GoodsTopBean goodsBean = new GoodsTopBean();
	int pagesize = 1;
	String pagenum = "15";
	String type = "load";
	List<GoodsTopBean.A> goodsBeanslist = new ArrayList<GoodsTopBean.A>();
	String uid, pid;
	MainPresenter mainPresenter;
	UserBean bean;
	ColloctionPresenter colloctionPresenter;
	int no_inter;
	private ConnectionChangeReceiver myReceiver;

	AppUpdatePresenter appUpdatePresenter;
	List<NewsKefuBeans> list = new ArrayList<NewsKefuBeans>();
	String toUid;
	String BaiId;
	String isUuid;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.fragment_goods;
	}

	@Override
	public void onMyActivityCreated() {
		// TODO Auto-generated method stub
		title.setText(R.string.h57);
		back.setVisibility(View.GONE);
		uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID, "");
		updatePresenter = new AppUpdatePresenter(this);
		AppUpdateBean appUpdateBean = new AppUpdateBean();
		colloctionPresenter = new ColloctionPresenter(this);
		updatePresenter.getInfo(appUpdateBean);
		goodsPresenter = new GoodsPresenter(this);
		goodsPresenter.AllQuery(uid + "", pagesize + "", pagenum);
		Log.e("hu    uid", uid);
		xlist.setPullLoadEnable(true);
		xlist.setPullRefreshEnable(true);
		xlist.setXListViewListener(this);
		pop = LayoutInflater.from(getActivity()).inflate(
				R.layout.dialog_no_interest, null);
		no_interest = (LinearLayout) pop.findViewById(R.id.no_interest);
		version = getAppVersionName(getActivity());

		// 客服
		appUpdatePresenter = new AppUpdatePresenter(this);
		appUpdatePresenter.onKefu();
		OnClick();
		autoLogin();
		adapter = new GoodsFragmentAdapter(getActivity(), goodsBeanslist,
				deleteonclick, collectiononclick);
		xlist.setAdapter(adapter);
		IntentFilter filter = new IntentFilter("newshead");
		IntentFilter loginfilter = new IntentFilter("LoginSuccess");
		IntentFilter AutoLoginfilter = new IntentFilter("AutoLogin");
		getActivity().registerReceiver(broadcastReceiver, filter);
		getActivity().registerReceiver(loginSuccess, loginfilter);
		getActivity().registerReceiver(AutoLogin, AutoLoginfilter);
		myReceiver = new ConnectionChangeReceiver();
		getActivity().registerReceiver(myReceiver,
				new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
	}

	BroadcastReceiver AutoLogin = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID,
					"");
			autoLogin();
		}
	};
	BroadcastReceiver loginSuccess = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			goodsBeanslist.clear();
			uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID,
					"");
			goodsPresenter.AllQuery(uid, pagesize + "", pagenum);
		}
	};
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			goodsBeanslist.clear();
			goodsPresenter.AllQuery("", pagesize + "", pagenum);
		}
	};

	private void autoLogin() {
		if ("".equals(uid) || uid == "") {
		} else {
			try {
				bean = new UserBean();
				mainPresenter = new MainPresenter(this);
				bean.setUid(uid);
				bean.setAutoLoginCode((String) SPUtils.get(getActivity(), null,
						SpPublicParams.Auto_Code, ""));
				mainPresenter.Autologin(bean);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	// 创建对话框方法dialog()

	private void OnClick() {
		// TODO Auto-generated method stub
		type_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						ActivityTypeTwoGoods.class);
				startActivity(intent);
			}
		});
		key_word.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						ActivityTypeDetail.class);
				startActivity(intent);
			}
		});
		carmar_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						ActivityCarmarSearch.class);
				intent.putExtra("from", "top");
				startActivity(intent);
			}
		});

		img_other.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if ("".equals(IsMobileNumPhone.isUid())
						|| IsMobileNumPhone.isUid() == null) {
					Intent intent = new Intent(getActivity(),
							LoginActivity.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent(getActivity(),
							ActivityCustomerService.class);
					startActivity(intent);
				}

			}
		});
		xlist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (arg2 - 1 != -1) {
					if ("p".equals(goodsBeanslist.get(arg2 - 1).getType())) {
						Intent intent = new Intent(getActivity(),
								GoodsDetail.class);
						intent.putExtra("pid", goodsBeanslist.get(arg2 - 1)
								.getInfo().get(0).getId());
						startActivity(intent);
					}
				}
			}
		});

	}

	OnClickListener deleteonclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			final int posion = (Integer) v.getTag();
			if (uid == "" || "".equals(uid)) {
				toast(getString(R.string.h1182));
				return;
			} else {
				no_interest.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v1) {
						// TODO Auto-generated method stub
						// MyToast.toast("delete");

						for (int i = 0; i < goodsBeanslist.get(posion)
								.getInfo().size(); i++) {
							System.out.println("goodsBeanslist"
									+ uid
									+ "\n"
									+ goodsBeanslist.get(posion).getInfo()
											.get(i).getId());
							colloctionPresenter.onDeleteNoInterested(uid,
									goodsBeanslist.get(posion).getInfo().get(i)
											.getId());
						}
						no_inter = posion;
						// ;
						adapter.notifyDataSetChanged();
						popupWindow.dismiss();

					}

				});
				popupWindow = new PopupWindow(pop, LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT);
				popupWindow.setOutsideTouchable(true);
				popupWindow.setBackgroundDrawable(new BitmapDrawable());
				int[] location = new int[2];
				v.getLocationOnScreen(location);
				popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]
						- ChangeToDP(100), location[1] - ChangeToDP(10));
			}
		}
	};
	OnClickListener collectiononclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (uid == null || uid == "") {
				toast(getString(R.string.h1182));
			} else {
				ColletionFenyeBeans model = new ColletionFenyeBeans();
				model.setUid(uid);
				model.setFType("1");
				pid = goodsBeanslist.get((Integer) v.getTag()).getInfo().get(0)
						.getId();
				System.out.println("pidpidpidpid" + pid);
				if ("p".equals(goodsBeanslist.get((int) v.getTag()).getType())) {
					// showNoticeDialog(model,v);
					// model.setIds(goodsBeanslist.get((Integer) v.getTag())
					// .getInfo().get(0).getId());
					// colloctionPresenter.add(model);
					showProgressDialog(getString(R.string.loading), true);
					model.setIds(goodsBeanslist.get((Integer) v.getTag())
							.getInfo().get(0).getId());
					colloctionPresenter.add(model);
					System.out.println("IntegerInteger"
							+ goodsBeanslist.get((int) v.getTag()).getType());
				}

			}
		}
	};

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = super.handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == AppUpdatePresenter.version_success) {
				AppUpdateBean appUpdateBean = (AppUpdateBean) entity.getData();
				SPUtils.put(MainApplication.getContext(), null,
						SpPublicParams.RMB_rate, appUpdateBean.getDOLLOR_RATE());// 汇率
				if (version.equals(appUpdateBean.getVersion() + "")) {

				} else {
					if ("1".equals(IsMobileNumPhone.isCheckd())
							|| "".equals(IsMobileNumPhone.isCheckd())) {
						onManager(appUpdateBean);
					}
				}
			} else if (entity.getEventType() == AppUpdatePresenter.version_fail) {
				// MyToast.toast("版本解析失败");
			}
			if (entity.getEventType() == MainPresenter.AutoLoginSuccess) {
				// AutoLoginSuccess(entity);

			} else if (entity.getEventType() == MainPresenter.AutoLoginFail
					|| entity.getEventType() == EVENT_TYPE_UNKNOWN) {
				SPUtils.put(MainApplication.context, null,
						SpPublicParams.USER_NAME, "");
				SPUtils.put(MainApplication.context, null,
						SpPublicParams.USERHEAD, "");
				SPUtils.put(MainApplication.context, null,
						SpPublicParams.NICK_NAME, "");
				SPUtils.put(MainApplication.context, null, SpPublicParams.UID,
						"");
				SPUtils.put(MainApplication.context, null, SpPublicParams.SEX,
						"");
				SPUtils.put(MainApplication.context, null,
						SpPublicParams.SIGNATURE, "");
				SPUtils.put(MainApplication.context, null,
						SpPublicParams.PHONE_MODEL, "");
				SPUtils.put(MainApplication.context, null, SpPublicParams.URL,
						"");
				SPUtils.put(getActivity(), null, SpPublicParams.Auto_Code,
						bean.getAutoLoginCode() + "");
				Intent intent = new Intent("newshead");
				getActivity().sendBroadcast(intent);
				Intent intent2 = new Intent("gotoshopcart");
				intent2.putExtra("index", 4);
				getActivity().sendBroadcast(intent2);
				// MyToast.toast(entity.getData() + "");
			}
			if (entity.getEventType() == GoodsPresenter.Top_success) {

				if (type.equals("load")) {
				} else {
					goodsBeanslist.clear();
				}
				goodsBean = (GoodsTopBean) entity.getData();
				goodsBeanslist.addAll(goodsBean.getList());
				adapter.notifyDataSetChanged();
				stop();
			} else if (entity.getEventType() == GoodsPresenter.Top_fail) {
				// MyToast.toast(entity.getData() + "");
				stop();

			}
			if (entity.getEventType() == ColloctionPresenter.ColloctAdd_success) {
				Intent intent = new Intent("UpDateCollection");
				getActivity().sendBroadcast(intent);
				// goodsPresenter.AllQuery(uid + "", pagesize + "", pagenum);
				Iterator<GoodsTopBean.A> iterator = goodsBeanslist.iterator();
				while (iterator.hasNext()) {
					GoodsTopBean.A getAList = iterator.next();
					if (getAList.getInfo().get(0).getId().equals(pid)) {
						if (!"0".equals(getAList.getInfo().get(0).getIs_fav())) {
							getAList.getInfo().get(0).setIs_fav("0");
							toast(getString(R.string.Cancel_collection));// 取消收藏
						} else {

							getAList.getInfo().get(0).setIs_fav("1");
							toast(getString(R.string.h1187));// 收藏成功

						}
						break;
					}
				}
				try {
					closeProgressDialog();
				} catch (Exception e) {
					// TODO: handle exception
				}

				adapter.notifyDataSetChanged();
				// MyToast.toast("" + entity.getData());
			} else if (entity.getEventType() == ColloctionPresenter.ColloctAdd_fail) {
				// MyToast.toast("" + entity.getData());
			} else if (entity.getEventType() == ColloctionPresenter.Delete_success) {
				goodsBeanslist.clear();
				goodsPresenter.AllQuery(uid + "", pagesize + "", pagenum);
				// goodsBeanslist.remove(no_inter);
				MyToast.toast(getString(R.string.h1190));
			} else if (entity.getEventType() == ColloctionPresenter.Delete_fai) {
				MyToast.toast("" + entity.getMsg());
			} 

		}
	}

	/**
	 * 版本更新
	 */
	public void onManager(AppUpdateBean appUpdateBean) {
		UpdateManager manager = new UpdateManager(getActivity(),
				appUpdateBean.getAndroid_update_log() + "",
				appUpdateBean.getDownloadurl());
		manager.checkUpdateInfo();
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		type = "clean";
		goodsPresenter.AllQuery(uid, "" + 1, pagenum);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		type = "load";
		pagesize++;
		goodsPresenter.AllQuery(uid, "" + pagesize, pagenum);
	}

	void stop() {
		xlist.stopRefresh();
		xlist.stopLoadMore();
	}

	void AutoLoginSuccess(ResultEntity entity) {
		// LoginController.setLoginState(new LoginedState());
		Intent intent2 = new Intent("newshead");
		getActivity().sendBroadcast(intent2);
		Intent intent = new Intent("LoginSuccess");
		getActivity().sendBroadcast(intent);
		UserBean bean = (UserBean) entity.getData();
		SPUtils.put(getActivity(), null, SpPublicParams.UID, bean.getUid() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.USER_NAME,
				bean.getUsername() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.PASSWORD,
				bean.getPassword() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.NICK_NAME,
				bean.getNickname() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.PHONE_MODEL,
				bean.getMobile() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.realname,
				bean.getRealname() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.USERHEAD,
				bean.getHead());
		SPUtils.put(getActivity(), null, SpPublicParams.SEX, bean.getSex() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.AcceptAddress,
				bean.getDefaultAddress() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.Company,
				bean.getCompany() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.Job, bean.getJobTitle()
				+ "");
		SPUtils.put(getActivity(), null, SpPublicParams.AcceptAddress,
				bean.getLocArea() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.USERHEAD,
				bean.getHead() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.WX, bean.getWeixin()
				+ "");
		SPUtils.put(getActivity(), null, SpPublicParams.IS_LOGINED, "1");
		SPUtils.put(getActivity(), null, SpPublicParams.Auto_Code,
				bean.getAutoLoginCode() + "");
		String time = String.valueOf((int) (Math.random() * 10));
		SPUtils.put(getActivity(), null, SpPublicParams.URL,
				GlobalConfig.IMAGE_HEAD + bean.getUid() + "&&random" + time);
	}
}
